/*
 * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

package java.lang;

import java.lang.ref.WeakReference;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
import java.util.stream.Collectors;

import jdk.internal.misc.CarrierThreadLocal;
import jdk.internal.misc.TerminatingThreadLocal;
import sun.security.action.GetPropertyAction;

/**
 * This class provides thread-local variables.  These variables differ from
 * their normal counterparts in that each thread that accesses one (via its
 * {@code get} or {@code set} method) has its own, independently initialized
 * copy of the variable.  {@code ThreadLocal} instances are typically private
 * static fields in classes that wish to associate state with a thread (e.g.,
 * a user ID or Transaction ID).
 *
 * <p>For example, the class below generates unique identifiers local to each
 * thread.
 * A thread's id is assigned the first time it invokes {@code ThreadId.get()}
 * and remains unchanged on subsequent calls.
 * <pre>
 * import java.util.concurrent.atomic.AtomicInteger;
 *
 * public class ThreadId {
 *     // Atomic integer containing the next thread ID to be assigned
 *     private static final AtomicInteger nextId = new AtomicInteger(0);
 *
 *     // Thread local variable containing each thread's ID
 *     private static final ThreadLocal&lt;Integer&gt; threadId =
 *         new ThreadLocal&lt;Integer&gt;() {
 *             &#64;Override protected Integer initialValue() {
 *                 return nextId.getAndIncrement();
 *         }
 *     };
 *
 *     // Returns the current thread's unique ID, assigning it if necessary
 *     public static int get() {
 *         return threadId.get();
 *     }
 * }
 * </pre>
 * <p>Each thread holds an implicit reference to its copy of a thread-local
 * variable as long as the thread is alive and the {@code ThreadLocal}
 * instance is accessible; after a thread goes away, all of its copies of
 * thread-local instances are subject to garbage collection (unless other
 * references to these copies exist).
 * @param <T> the type of the thread local's value
 *
 * @author  Josh Bloch and Doug Lea
 * @since   1.2
 */
public class ThreadLocal<T> {

    private static final boolean TRACE_VTHREAD_LOCALS = traceVirtualThreadLocals();

    /**
     * <p>ThreadLocals rely on per-thread linear-probe hash maps attached
     * to each thread (Thread.threadLocals and
     * inheritableThreadLocals).  The ThreadLocal objects act as keys,
     * searched via threadLocalHashCode.  This is a custom hash code
     * (useful only within ThreadLocalMaps) that eliminates collisions
     * in the common case where consecutively constructed ThreadLocals
     * are used by the same threads, while remaining well-behaved in
     * less common cases.
     *
     * <p>ThreadLocal 的实现依赖于每个线程内部维护的 线性探测哈希表（通过 Thread 类的 threadLocals 和 inheritableThreadLocals 字段实现）。
     *
     *
     * <p>其核心机制如下：
     * <ul>
     *     <li>键值设计：ThreadLocal 对象本身作为键，通过 threadLocalHashCode 实现哈希查找</li>
     *     <li>定制哈希算法：采用仅适用于 ThreadLocalMap 的特殊哈希码，避免同一线程连续使用多个 ThreadLocal 实例时的哈希冲突（常见场景优化），在非常用场景下仍能保持稳定表现</li>
     * </ul>
     */
    private final int threadLocalHashCode = nextHashCode();

    /**
     * The next hash code to be given out. Updated atomically. Starts at
     * zero.
     *
     * <p>下一个要给出的哈希码。原子更新。从零开始。
     */
    private static AtomicInteger nextHashCode = new AtomicInteger();

    /**
     * <p>The difference between successively generated hash codes - turns
     * implicit sequential thread-local IDs into near-optimally spread
     * multiplicative hash values for power-of-two-sized tables.
     *
     * <p>连续生成的哈希码之间的差异——将隐式顺序线程局部ID转化为接近最优分布的乘法哈希值，以获得两个大小表的幂。
     */
    private static final int HASH_INCREMENT = 0x61c88647;

    /**
     * Returns the next hash code.
     */
    private static int nextHashCode() {
        return nextHashCode.getAndAdd(HASH_INCREMENT);
    }

    /**
     * Returns the current thread's "initial value" for this
     * thread-local variable.  This method will be invoked the first
     * time a thread accesses the variable with the {@link #get}
     * method, unless the thread previously invoked the {@link #set}
     * method, in which case the {@code initialValue} method will not
     * be invoked for the thread.  Normally, this method is invoked at
     * most once per thread, but it may be invoked again in case of
     * subsequent invocations of {@link #remove} followed by {@link #get}.
     *
     * @implSpec
     * This implementation simply returns {@code null}; if the
     * programmer desires thread-local variables to have an initial
     * value other than {@code null}, then either {@code ThreadLocal}
     * can be subclassed and this method overridden or the method
     * {@link ThreadLocal#withInitial(Supplier)} can be used to
     * construct a {@code ThreadLocal}.
     *
     * @return the initial value for this thread-local
     * @see #withInitial(java.util.function.Supplier)
     */
    protected T initialValue() {
        return null;
    }

    /**
     * Creates a thread local variable. The initial value of the variable is
     * determined by invoking the {@code get} method on the {@code Supplier}.
     *
     * @param <S> the type of the thread local's value
     * @param supplier the supplier to be used to determine the initial value
     * @return a new thread local variable
     * @throws NullPointerException if the specified supplier is null
     * @since 1.8
     */
    public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier) {
        return new SuppliedThreadLocal<>(supplier);
    }

    /**
     * Creates a thread local variable.
     * @see #withInitial(java.util.function.Supplier)
     */
    public ThreadLocal() {
    }

    /**
     * Returns the value in the current thread's copy of this
     * thread-local variable.  If the variable has no value for the
     * current thread, it is first initialized to the value returned
     * by an invocation of the {@link #initialValue} method.
     *
     * <p>返回当前线程的线程局部变量副本中的值。
     * 若当前线程尚未对该变量赋值，则系统会先调用 initialValue 方法进行初始化赋值。
     *
     * @return the current thread's value of this thread-local
     */
    public T get() {
        return get(Thread.currentThread());
    }

    /**
     * Returns the value in the current carrier thread's copy of this
     * thread-local variable.
     */
    T getCarrierThreadLocal() {
        assert this instanceof CarrierThreadLocal<T>;
        return get(Thread.currentCarrierThread());
    }

    /**
     * <p>返回指定线程的线程局部变量副本中的值
     * 若当前线程尚未对该变量赋值，则系统会先调用 initialValue 方法进行初始化赋值。
     *
     * @param t 线程
     */
    private T get(Thread t) {
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T) e.value;
                return result;
            }
        }
        // map == null，即 map 不存在时
        // 或者 map 存在，但是当前 ThreadLocal 实例没有对应的 Key-Value对 时
        // 表示当前线程不存在局部变量，设置初始值并返回
        return setInitialValue(t);
    }

    /**
     * Returns {@code true} if there is a value in the current carrier thread's copy of
     * this thread-local variable, even if that values is {@code null}.
     *
     * @return {@code true} if current carrier thread has associated value in this
     *         thread-local variable; {@code false} if not
     */
    boolean isCarrierThreadLocalPresent() {
        assert this instanceof CarrierThreadLocal<T>;
        return isPresent(Thread.currentCarrierThread());
    }

    private boolean isPresent(Thread t) {
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            return map.getEntry(this) != null;
        } else {
            return false;
        }
    }

    /**
     * <p>Variant of set() to establish initialValue. Used instead
     * of set() in case user has overridden the set() method.
     *
     * <p>此方法是 set() 的变体实现，专门用于初始化线程局部变量的初始值。
     * 当开发者重写了 set() 方法时，应当使用此方法替代 set() 来完成初始化操作。
     *
     * <p>设置 ThreadLocal 关联的初始值并返回
     *
     * @return the initial value
     */
    private T setInitialValue(Thread t) {
        T value = initialValue();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            map.set(this, value);
        } else {
            createMap(t, value);
        }
        if (this instanceof TerminatingThreadLocal<?> ttl) {
            TerminatingThreadLocal.register(ttl);
        }
        if (TRACE_VTHREAD_LOCALS) {
            dumpStackIfVirtualThread();
        }
        return value;
    }

    /**
     * <p>Sets the current thread's copy of this thread-local variable
     * to the specified value.  Most subclasses will have no need to
     * override this method, relying solely on the {@link #initialValue}
     * method to set the values of thread-locals.
     *
     * <p>将当前线程的线程局部变量副本设置为指定值。大多数子类无需重写此方法，仅需依赖 initialValue 方法即可完成线程局部变量的初始化赋值。
     *
     * @param value the value to be stored in the current thread's copy of
     *        this thread-local.
     */
    public void set(T value) {
        set(Thread.currentThread(), value);
        if (TRACE_VTHREAD_LOCALS) {
            dumpStackIfVirtualThread();
        }
    }

    void setCarrierThreadLocal(T value) {
        assert this instanceof CarrierThreadLocal<T>;
        set(Thread.currentCarrierThread(), value);
    }

    private void set(Thread t, T value) {
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            // value 绑定到 ThreadLocal 实例
            map.set(this, value);
        } else {
            // 如果当前线程没有 ThreadLocalMap 成员实例
            // 创建一个 ThreadLocalMap 实例，然后作为成员关联到 t（thread实例）
            createMap(t, value);
        }
    }

    /**
     * Removes the current thread's value for this thread-local
     * variable.  If this thread-local variable is subsequently
     * {@linkplain #get read} by the current thread, its value will be
     * reinitialized by invoking its {@link #initialValue} method,
     * unless its value is {@linkplain #set set} by the current thread
     * in the interim.  This may result in multiple invocations of the
     * {@code initialValue} method in the current thread.
     *
     * <p>移除当前线程在此线程局部变量中的绑定值。后续若当前线程再次读取该变量时：
     * <ul>
     *      <li>默认行为：系统将调用 initialValue 方法重新初始化值  </li>
     *      <li>例外情况：若期间当前线程主动通过 set 方法赋值，则采用设定值  </li>
     *      <li>潜在影响：可能导致当前线程内多次调用 initialValue 方法  </li>
     * </ul>
     *
     * @since 1.5
     */
     public void remove() {
         remove(Thread.currentThread());
     }

     void removeCarrierThreadLocal() {
         assert this instanceof CarrierThreadLocal<T>;
         remove(Thread.currentCarrierThread());
     }

     private void remove(Thread t) {
         ThreadLocalMap m = getMap(t);
         if (m != null) {
             m.remove(this);
         }
     }

    /**
     * Get the map associated with a ThreadLocal. Overridden in
     * InheritableThreadLocal.
     *
     * <p>获取方法参数指定的线程 t 的 ThreadLocalMap 成员
     *
     * @param  t the current thread
     * @return the map
     */
    ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }

    /**
     * Create the map associated with a ThreadLocal. Overridden in
     * InheritableThreadLocal.
     *
     * <p>线程 t 创建一个 ThreadLocalMap 成员，并为新的 Map 成员设置第一个 Key-Value 对，Key 为当前的 ThreadLocal 实例
     *
     * @param t the current thread
     * @param firstValue value for the initial entry of the map
     */
    void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

    /**
     * Factory method to create map of inherited thread locals.
     * Designed to be called only from Thread constructor.
     *
     * @param  parentMap the map associated with parent thread
     * @return a map containing the parent's inheritable bindings
     */
    static ThreadLocalMap createInheritedMap(ThreadLocalMap parentMap) {
        return new ThreadLocalMap(parentMap);
    }

    /**
     * Method childValue is visibly defined in subclass
     * InheritableThreadLocal, but is internally defined here for the
     * sake of providing createInheritedMap factory method without
     * needing to subclass the map class in InheritableThreadLocal.
     * This technique is preferable to the alternative of embedding
     * instanceof tests in methods.
     */
    T childValue(T parentValue) {
        throw new UnsupportedOperationException();
    }

    /**
     * An extension of ThreadLocal that obtains its initial value from
     * the specified {@code Supplier}.
     *
     * <p>这是 ThreadLocal 的一个扩展实现类，其特性在于通过指定的 Supplier（供应者） 来获取初始值。
     *
     */
    static final class SuppliedThreadLocal<T> extends ThreadLocal<T> {

        private final Supplier<? extends T> supplier;

        SuppliedThreadLocal(Supplier<? extends T> supplier) {
            this.supplier = Objects.requireNonNull(supplier);
        }

        @Override
        protected T initialValue() {
            return supplier.get();
        }
    }

    /**
     * <p>ThreadLocalMap is a customized hash map suitable only for
     * maintaining thread local values. No operations are exported
     * outside of the ThreadLocal class. The class is package private to
     * allow declaration of fields in class Thread.  To help deal with
     * very large and long-lived usages, the hash table entries use
     * WeakReferences for keys. However, since reference queues are not
     * used, stale entries are guaranteed to be removed only when
     * the table starts running out of space.
     *
     * <p>ThreadLocalMap 是一种定制化的哈希映射结构，专门用于维护线程局部变量值。
     * 其所有操作都封装在 ThreadLocal 类内部，不对外暴露。该类采用包级私有（package-private）访问权限，以便在 Thread 类中声明相应字段。
     *
     * <p>为处理大规模且长期存活的使用场景，该哈希表条目采用 WeakReference 作为键的引用类型。但需要注意：
     * 由于未使用引用队列（reference queues）只有当哈希表开始耗尽存储空间时，才会保证清理过期的条目
     */
    static class ThreadLocalMap {

        /**
         * <p>The entries in this hash map extend WeakReference, using
         * its main ref field as the key (which is always a
         * ThreadLocal object).  Note that null keys (i.e. entry.get()
         * == null) mean that the key is no longer referenced, so the
         * entry can be expunged from table.  Such entries are referred to
         * as "stale entries" in the code that follows.
         *
         * <p>该哈希映射中的条目继承自 WeakReference，使用其主引用字段 ref 作为键（该键始终是 ThreadLocal 对象）。
         * 需特别注意：
         * <p>空键处理：当键为空（即 entry.get() == null）时，表示该键已不再被引用，此时条目可从表中清除
         * <p>术语对应：此类条目在后续代码中统称为 "陈旧条目"（stale entries）
         */
        static class Entry extends WeakReference<ThreadLocal<?>> {

            /**
             * <p>The value associated with this ThreadLocal.
             *
             * <p>与此 ThreadLocal 关联的值。
             *
             **/
            Object value;

            Entry(ThreadLocal<?> k, Object v) {
                super(k);
                value = v;
            }
        }

        /**
         * <p>The initial capacity -- MUST be a power of two.
         *
         * <p>初始容量，必须是 2 的次幂
         */
        private static final int INITIAL_CAPACITY = 16;

        /**
         * <p>The table, resized as necessary.
         * table.length MUST always be a power of two.
         *
         * <p>底层数组，底层数组长度必须为 2 的次幂
         */
        private Entry[] table;

        /**
         * <p>The number of entries in the table.
         *
         * <p>map 中的条目数量
         */
        private int size = 0;

        /**
         * <p>The next size value at which to resize.
         *
         * <p>扩容因子，默认值为 0，哈希表容量在达到扩容因子时进行扩容
         */
        private int threshold; // Default to 0

        /**
         * <p>Set the resize threshold to maintain at worst a 2/3 load factor.
         *
         * <p>设置扩容因子为 2/3
         */
        private void setThreshold(int len) {
            threshold = len * 2 / 3;
        }

        /**
         * Increment i modulo len.
         */
        private static int nextIndex(int i, int len) {
            return ((i + 1 < len) ? i + 1 : 0);
        }

        /**
         * Decrement i modulo len.
         */
        private static int prevIndex(int i, int len) {
            return ((i - 1 >= 0) ? i - 1 : len - 1);
        }

        /**
         * Construct a new map without a table.
         */
        private ThreadLocalMap() {
        }

        /**
         * Construct a new map initially containing (firstKey, firstValue).
         * ThreadLocalMaps are constructed lazily, so we only create
         * one when we have at least one entry to put in it.
         */
        ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
            table = new Entry[INITIAL_CAPACITY];
            int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
            table[i] = new Entry(firstKey, firstValue);
            size = 1;
            setThreshold(INITIAL_CAPACITY);
        }

        /**
         * Construct a new map including all Inheritable ThreadLocals
         * from given parent map. Called only by createInheritedMap.
         *
         * @param parentMap the map associated with parent thread.
         */
        private ThreadLocalMap(ThreadLocalMap parentMap) {
            Entry[] parentTable = parentMap.table;
            int len = parentTable.length;
            setThreshold(len);
            table = new Entry[len];

            for (Entry e : parentTable) {
                if (e != null) {
                    @SuppressWarnings("unchecked")
                    ThreadLocal<Object> key = (ThreadLocal<Object>) e.get();
                    if (key != null) {
                        Object value = key.childValue(e.value);
                        Entry c = new Entry(key, value);
                        int h = key.threadLocalHashCode & (len - 1);
                        while (table[h] != null)
                            h = nextIndex(h, len);
                        table[h] = c;
                        size++;
                    }
                }
            }
        }

        /**
         * Returns the number of elements in the map.
         */
        int size() {
            return size;
        }

        /**
         * Get the entry associated with key.  This method
         * itself handles only the fast path: a direct hit of existing
         * key. It otherwise relays to getEntryAfterMiss.  This is
         * designed to maximize performance for direct hits, in part
         * by making this method readily inlinable.
         *
         * <p>通过方法参数的 ThreadLocal 的 key 获取关联的条目。
         * 此方法本身仅处理快速路径：直接命中现有键。
         * 否则，它会中继到 getEntryAfterMiss。
         *
         * <p>这旨在最大限度地提高直接命中的性能，部分方法是使此方法易于内联
         *
         * @param  key the thread local object
         * @return the entry associated with key, or null if no such
         */
        private Entry getEntry(ThreadLocal<?> key) {
            // 根据入参的 ThreadLocal 的 key 的 hashCode 计算桶数组索引位置
            int i = key.threadLocalHashCode & (table.length - 1);
            Entry e = table[i];
            // 如果桶数组中该索引位置的元素不为 null，并且元素 key 与入参中的 key 匹配
            if (e != null && e.refersTo(key)) {
                return e;
            } else {
                return getEntryAfterMiss(key, i, e);
            }
        }

        /**
         * Version of getEntry method for use when key is not found in
         * its direct hash slot.
         *
         * <p>当在其直接哈希槽中找不到键时使用的 getEntry 方法版本。
         *
         * @param  key the thread local object
         * @param  i the table index for key's hash code，根据 key 的哈希码计算出的桶数组索引
         * @param  e the entry at table[i]，根据计算出的索引获取到的桶数组中的元素
         *
         * @return the entry associated with key, or null if no such
         */
        private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {
            Entry[] tab = table;
            int len = tab.length;

            while (e != null) {
                // 检查当前条目是否引用了指定的 ThreadLocal 实例，如果是，则直接返回该条目。
                if (e.refersTo(key)) {
                    return e;
                }
                if (e.refersTo(null)) {
                    expungeStaleEntry(i);
                } else {
                    i = nextIndex(i, len);
                }
                e = tab[i];
            }
            return null;
        }

        /**
         * Set the value associated with key.
         *
         * @param key the thread local object
         * @param value the value to be set
         */
        private void set(ThreadLocal<?> key, Object value) {

            // 此处未采用类似 get() 方法的快速路径实现，原因在于：
            // 1. 使用频率分析：set() 用于 新建条目 的场景至少与 替换现有值 同样常见
            // 2. 失败率评估：在新建条目场景下，快速路径的 失败率会显著高于成功率

            // We don't use a fast path as with get() because it is at
            // least as common to use set() to create new entries as
            // it is to replace existing ones, in which case, a fast
            // path would fail more often than not.

            Entry[] tab = table;
            int len = tab.length;
            // 根据 hashCode 计算出 Entry 在数组中的索引位置
            int i = key.threadLocalHashCode & (len-1);

            // 从槽点 i 开始向后循环搜索，找空余槽点（空余位置）或者找现有槽点
            // 若没有现有槽点，则必定有空余槽点，因为没有空间时会扩容
            for (Entry e = tab[i]; e != null; e = tab[i = nextIndex(i, len)]) {

                // 找到现有槽点：Key 值为 ThreadLocal 实例
                if (e.refersTo(key)) {
                    e.value = value;
                    return;
                }
                // 找到异常槽点：槽点被 GC 掉，重设 Key 值和 Value 值
                if (e.refersTo(null)) {
                    replaceStaleEntry(key, value, i);
                    return;
                }
            }

            // 没有找到现有的槽点，增加新的 Entry
            tab[i] = new Entry(key, value);
            // 设置 ThreadLocal 数量
            int sz = ++size;
            // 清理 Key 为 null 的无效 Entry
            // 没有可清理的 Entry，并且现有条目数量大于扩容因子值，进行扩容
            if (!cleanSomeSlots(i, sz) && sz >= threshold) {
                rehash();
            }
        }

        /**
         * Remove the entry for key.
         */
        private void remove(ThreadLocal<?> key) {
            Entry[] tab = table;
            int len = tab.length;
            int i = key.threadLocalHashCode & (len-1);
            for (Entry e = tab[i];
                 e != null;
                 e = tab[i = nextIndex(i, len)]) {
                if (e.refersTo(key)) {
                    e.clear();
                    expungeStaleEntry(i);
                    return;
                }
            }
        }

        /**
         * Replace a stale entry encountered during a set operation
         * with an entry for the specified key.  The value passed in
         * the value parameter is stored in the entry, whether or not
         * an entry already exists for the specified key.
         *
         * As a side effect, this method expunges all stale entries in the
         * "run" containing the stale entry.  (A run is a sequence of entries
         * between two null slots.)
         *
         * @param  key the key
         * @param  value the value to be associated with key
         * @param  staleSlot index of the first stale entry encountered while
         *         searching for key.
         */
        private void replaceStaleEntry(ThreadLocal<?> key, Object value,
                                       int staleSlot) {
            Entry[] tab = table;
            int len = tab.length;
            Entry e;

            // Back up to check for prior stale entry in current run.
            // We clean out whole runs at a time to avoid continual
            // incremental rehashing due to garbage collector freeing
            // up refs in bunches (i.e., whenever the collector runs).
            int slotToExpunge = staleSlot;
            for (int i = prevIndex(staleSlot, len);
                 (e = tab[i]) != null;
                 i = prevIndex(i, len))
                if (e.refersTo(null))
                    slotToExpunge = i;

            // Find either the key or trailing null slot of run, whichever
            // occurs first
            for (int i = nextIndex(staleSlot, len);
                 (e = tab[i]) != null;
                 i = nextIndex(i, len)) {
                // If we find key, then we need to swap it
                // with the stale entry to maintain hash table order.
                // The newly stale slot, or any other stale slot
                // encountered above it, can then be sent to expungeStaleEntry
                // to remove or rehash all of the other entries in run.
                if (e.refersTo(key)) {
                    e.value = value;

                    tab[i] = tab[staleSlot];
                    tab[staleSlot] = e;

                    // Start expunge at preceding stale entry if it exists
                    if (slotToExpunge == staleSlot)
                        slotToExpunge = i;
                    cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
                    return;
                }

                // If we didn't find stale entry on backward scan, the
                // first stale entry seen while scanning for key is the
                // first still present in the run.
                if (e.refersTo(null) && slotToExpunge == staleSlot)
                    slotToExpunge = i;
            }

            // If key not found, put new entry in stale slot
            tab[staleSlot].value = null;
            tab[staleSlot] = new Entry(key, value);

            // If there are any other stale entries in run, expunge them
            if (slotToExpunge != staleSlot)
                cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
        }

        /**
         * Expunge a stale entry by rehashing any possibly colliding entries
         * lying between staleSlot and the next null slot.  This also expunges
         * any other stale entries encountered before the trailing null.  See
         * Knuth, Section 6.4
         *
         * <p>通过重新哈希位于 staleSlot 和下一个空槽之间可能发生冲突的条目，来清除陈旧的条目。
         * 此操作还会清除在遇到末尾空槽之前的所有其他陈旧条目。
         *
         * <p>具体算法参见 Knuth 著作第 6.4 节。
         *
         * @param staleSlot index of slot known to have null key
         *
         * @return the index of the next null slot after staleSlot
         * (all between staleSlot and this slot will have been checked
         * for expunging).
         */
        private int expungeStaleEntry(int staleSlot) {
            Entry[] tab = table;
            int len = tab.length;

            // expunge entry at staleSlot
            tab[staleSlot].value = null;
            tab[staleSlot] = null;
            size--;

            // Rehash until we encounter null
            Entry e;
            int i;
            for (i = nextIndex(staleSlot, len);
                 (e = tab[i]) != null;
                 i = nextIndex(i, len)) {
                ThreadLocal<?> k = e.get();
                if (k == null) {
                    e.value = null;
                    tab[i] = null;
                    size--;
                } else {
                    int h = k.threadLocalHashCode & (len - 1);
                    if (h != i) {
                        tab[i] = null;

                        // Unlike Knuth 6.4 Algorithm R, we must scan until
                        // null because multiple entries could have been stale.
                        while (tab[h] != null)
                            h = nextIndex(h, len);
                        tab[h] = e;
                    }
                }
            }
            return i;
        }

        /**
         * Heuristically scan some cells looking for stale entries.
         * This is invoked when either a new element is added, or
         * another stale one has been expunged. It performs a
         * logarithmic number of scans, as a balance between no
         * scanning (fast but retains garbage) and a number of scans
         * proportional to number of elements, that would find all
         * garbage but would cause some insertions to take O(n) time.
         *
         * <p>启发式扫描部分单元格以查找陈旧条目。
         * 此操作在添加新元素或清除另一个陈旧条目时触发。
         * 该方法执行对数级别的扫描次数，以在完全不扫描（速度快但会残留垃圾）和与元素数量成正比的扫描次数（能发现所有垃圾但会导致某些插入操作耗时 O(n)）之间取得平衡。
         *
         * @param i a position known NOT to hold a stale entry. The
         * scan starts at the element after i.
         * <br>
         *          一个已知不持有过时条目的索引位置。扫描从 i 之后的元素开始。
         *
         * @param n scan control: {@code log2(n)} cells are scanned,
         * unless a stale entry is found, in which case
         * {@code log2(table.length)-1} additional cells are scanned.
         * When called from insertions, this parameter is the number
         * of elements, but when from replaceStaleEntry, it is the
         * table length. (Note: all this could be changed to be either
         * more or less aggressive by weighting n instead of just
         * using straight log n. But this version is simple, fast, and
         * seems to work well.)
         * <br>
         *          扫描控制策略：默认扫描 log2(n) 个单元格，若发现陈旧条目则额外扫描 log2(table.length)-1 个单元格。
         *          当被插入操作调用时，参数 n 表示元素数量；而被 replaceStaleEntry 调用时，n 表示哈希表长度。
         *          （注：本算法可通过调整 n 的权重系数而非直接使用对数来调节扫描强度，但当前版本简洁高效且表现良好。）
         *
         * @return true if any stale entries have been removed.
         */
        private boolean cleanSomeSlots(int i, int n) {
            boolean removed = false;
            Entry[] tab = table;
            int len = tab.length;
            do {
                i = nextIndex(i, len);
                Entry e = tab[i];
                if (e != null && e.refersTo(null)) {
                    n = len;
                    removed = true;
                    i = expungeStaleEntry(i);
                }
            } while ( (n >>>= 1) != 0);
            return removed;
        }

        /**
         * Re-pack and/or re-size the table. First scan the entire
         * table removing stale entries. If this doesn't sufficiently
         * shrink the size of the table, double the table size.
         */
        private void rehash() {
            expungeStaleEntries();

            // Use lower threshold for doubling to avoid hysteresis
            if (size >= threshold - threshold / 4)
                resize();
        }

        /**
         * Double the capacity of the table.
         */
        private void resize() {
            Entry[] oldTab = table;
            int oldLen = oldTab.length;
            int newLen = oldLen * 2;
            Entry[] newTab = new Entry[newLen];
            int count = 0;

            for (Entry e : oldTab) {
                if (e != null) {
                    ThreadLocal<?> k = e.get();
                    if (k == null) {
                        e.value = null; // Help the GC
                    } else {
                        int h = k.threadLocalHashCode & (newLen - 1);
                        while (newTab[h] != null)
                            h = nextIndex(h, newLen);
                        newTab[h] = e;
                        count++;
                    }
                }
            }

            setThreshold(newLen);
            size = count;
            table = newTab;
        }

        /**
         * Expunge all stale entries in the table.
         */
        private void expungeStaleEntries() {
            Entry[] tab = table;
            int len = tab.length;
            for (int j = 0; j < len; j++) {
                Entry e = tab[j];
                if (e != null && e.refersTo(null))
                    expungeStaleEntry(j);
            }
        }
    }


    /**
     * Reads the value of the jdk.traceVirtualThreadLocals property to determine if
     * a stack trace should be printed when a virtual thread sets a thread local.
     *
     * <p>读取 jdk.traceVirtualThreadLocals 系统属性的值，用于决定当虚拟线程设置线程局部变量时是否应打印堆栈跟踪信息。
     */
    private static boolean traceVirtualThreadLocals() {
        String propValue = GetPropertyAction.privilegedGetProperty("jdk.traceVirtualThreadLocals");
        return (propValue != null)
                && (propValue.isEmpty() || Boolean.parseBoolean(propValue));
    }

    /**
     * Print a stack trace if the current thread is a virtual thread.
     */
    static void dumpStackIfVirtualThread() {
        if (Thread.currentThread() instanceof VirtualThread vthread) {
            try {
                var stack = StackWalkerHolder.STACK_WALKER.walk(s ->
                        s.skip(1)  // skip caller
                         .collect(Collectors.toList()));

                // switch to carrier thread to avoid recursive use of thread-locals
                vthread.executeOnCarrierThread(() -> {
                    System.out.println(vthread);
                    for (StackWalker.StackFrame frame : stack) {
                        System.out.format("    %s%n", frame.toStackTraceElement());
                    }
                    return null;
                });
            } catch (Exception e) {
                throw new InternalError(e);
            }
        }
    }

    private static class StackWalkerHolder {
        static final StackWalker STACK_WALKER = StackWalker.getInstance();
    }
}
